package com.example.blog.controller;

import com.example.blog.common.AppVariable;
import com.example.blog.common.PasswordUtils;
import com.example.blog.common.ResultAjax;
import com.example.blog.model.UserInfo;
import com.example.blog.model.vo.UserInfoVO;
import com.example.blog.service.IUserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author YJ
 * @Date 2023/9/5 15:32
 * Description:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @PostMapping("/reg")
    public ResultAjax reg(UserInfo userInfo) {
        //非空校验
        if (userInfo == null
                || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())) {
            return ResultAjax.fail(-1, "非法参数");
        }
        //密码加盐
        userInfo.setPassword(PasswordUtils.encrypt(userInfo.getPassword()));
        int row = userService.reg(userInfo);
        return ResultAjax.success(row);
    }

    @GetMapping("/login")
    public ResultAjax login(HttpServletRequest request, UserInfoVO userInfoVO) {
        //1.参数校验
        if (userInfoVO == null
                || !StringUtils.hasLength(userInfoVO.getUsername())
                || !StringUtils.hasLength(userInfoVO.getPassword())) {
            return ResultAjax.fail(-1, "非法参数");
        }
        //2.根据用户名查询
        UserInfo userInfo = userService.selectByUserName(userInfoVO.getUsername());
        if (userInfo == null || userInfo.getUserId() == 0) {
            //不存在此用户
            return ResultAjax.fail(-2, "用户名或密码错误！");
        }
        //3.将在数据库查到的用户密码与前端密码进行比较
        //userInfoVO.getPassword().equals(userInfo.getPassword())
        //加盐解密
        if (!PasswordUtils.decrypt(userInfoVO.getPassword(),userInfo.getPassword())) {
            //密码错误
            return ResultAjax.fail(-2, "用户名或密码错误！");
        }
        //4.登录成功后，设置session
        HttpSession session = request.getSession();
        session.setAttribute(AppVariable.SESSION_USER_KEY, userInfo);
        //5.返回结果
        return ResultAjax.success(1);
    }

    /**
     * 注销
     *
     * @param request 获取session
     * @return
     */
    @PostMapping("/logout")
    public ResultAjax logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppVariable.SESSION_USER_KEY) != null) {
            session.removeAttribute(AppVariable.SESSION_USER_KEY);
        }
        return ResultAjax.success(1);
    }


}
